#include <vector>
#include <unordered_map>

using std::unordered_map;
using std::vector;

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if (k == 0) {
            return false;
        }
        int first = nums[0];
        int index = 0;
        unordered_map<int, int> map;
        while (index < nums.size() && index < k + 1) {
            map[nums[index]]++;
            if (map[nums[index]] > 1) {
                return true;
            }
            index++;
        }
        while (index < nums.size()) {
            map[first]--;
            first = nums[index - k];
            if (map[nums[index]] > 0) {
                return true;
            }
            else {
                map[nums[index]]++;
            }
            index++;
        }
        return false;
    }
};